/*
 *  Copyright 2009 Mikhail Titov.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.raven.statdb.impl;

import javax.script.Bindings;
import javax.script.ScriptException;
import org.raven.expr.Expression;
import org.raven.statdb.Aggregation;
import org.raven.statdb.AggregationFunction;
import org.weda.services.TypeConverter;

/**
 *
 * @author Mikhail Titov
 */
public class SelectEntryAggregation
{
    private final AggregationFunction aggregationFunction;
    private final Expression expression;
    private final TypeConverter converter;
    private Aggregation aggregation;

    public SelectEntryAggregation(
            AggregationFunction aggregationFunction, Expression expression, TypeConverter converter)
    {
        this.aggregationFunction = aggregationFunction;
        this.expression = expression;
        this.converter = converter;
    }

    public void aggregate(Bindings bindings) throws ScriptException
    {
        Object value = expression.eval(bindings);
        Double doubleValue = converter.convert(Double.class, value, null);
        if (aggregation==null)
            aggregation = aggregationFunction.createAggregation(0, doubleValue);
        else
            aggregation.aggregate(doubleValue);
    }

    public void reset()
    {
        aggregation = null;
    }

    public double getValue()
    {
        return aggregation.getValue();
    }

}
